<template>
  <div class="reservation-container">
    <div class="card-header">
      <h2>{{ roomName }}</h2>
      <div class="header-decoration"></div>
    </div>
    
    <el-form :model="form" label-width="100px" class="reservation-form">
      <div class="form-header">
        <el-form-item label="预约日期" class="date-picker-item">
          <el-date-picker
            v-model="form.bookingDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            @change="fetchTimeSlots"
            class="custom-date-picker"
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-form-item label="参与人数" class="number-input-item">
            <el-input-number 
              v-model="form.participants" 
              :min="1" 
              class="custom-number-input"
              controls-position="right"
            />
          </el-form-item>
          
          <div class="action-buttons">
            <el-button 
              type="primary" 
              class="submit-button"
              @click="submitForm"
              :disabled="!hasSelectedTimeSlot"
            >
              <el-icon><Check /></el-icon>
              确认预约
            </el-button>
            <el-button 
              class="cancel-button"
              @click="$emit('close')"
            >
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="time-slots-container" v-if="isShow">
        <div class="time-slots-grid">
          <div 
            v-for="(slot, index) in timeSlots" 
            :key="index"
            class="time-slot-card" 
            :class="[slot.status, { 'selected': slot.selected }]"
            @click="toggleTimeSlot(slot, index)"
          >
            <div class="time-slot-content">
              <div class="time-label">{{ slot.time }}</div>
              <div class="status-indicator" :class="slot.status">
                <el-icon v-if="slot.status === 'locked'"><Lock /></el-icon>
                <el-icon v-else-if="slot.status === 'booked'"><Timer /></el-icon>
                <el-icon v-else><Check /></el-icon>
                <span>{{ slot.status === 'locked' ? '已锁定' : 
                  slot.status === 'booked' ? '已预约' : '空闲' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useOrderStore } from '../stores/OrderStore'
import { useUserStore } from '../stores/UserStore'
import { Lock, Timer, Check, Close } from '@element-plus/icons-vue'

const orderStore = useOrderStore()
const userStore = useUserStore()

const isShow = ref(false)

const props = defineProps({
  roomId: {
    type: Number,
    required: true
  },
  roomName: {
    type: String,
    required: true
  }
})

const form = ref({
  bookingDate: '',
  startHour: '',
  endHour: '',
  participants: 1
})

const timeSlots = ref(
  Array.from({ length: 13 }, (_, i) => {
    const hour = i + 8 // 从8点开始
    return {
      time: `${hour.toString().padStart(2, '0')}:00 - ${(hour + 1).toString().padStart(2, '0')}:00`,
      status: hour === 21 ? 'locked' : 'available', // 21:00-22:00设置为锁定状态
      selected: false,
      hour: hour
    }
  })
)

const emit = defineEmits(['close'])

// 添加计算属性检查是否有时段被选中
const hasSelectedTimeSlot = computed(() => {
  return timeSlots.value.some(slot => slot.selected)
})

// 获取当前日期，格式为 YYYY-MM-DD
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取60天后的日期
const getMaxDate = () => {
  const now = new Date()
  const maxDate = new Date(now)
  maxDate.setDate(now.getDate() + 60)
  return maxDate
}

// 禁用今天之前和60天后的日期
const disabledDate = (time) => {
  const currentDate = new Date(getCurrentDate())
  const maxDate = getMaxDate()
  return time.getTime() < currentDate.getTime() || time.getTime() > maxDate.getTime()
}

// 检查当前时间是否已过
const isCurrentTimePassed = (hour) => {
  const now = new Date()
  const currentDate = getCurrentDate()
  if (form.value.bookingDate === currentDate) {
    return hour <= now.getHours()
  }
  return false
}

const fetchTimeSlots = async () => {

  const res = await orderStore.getStatues(props.roomId, form.value.bookingDate)
  updateTimeSlots(res)
  isShow.value = true
}

// 根据后端返回的锁定时间段更新状态
const updateTimeSlots = (res) => {
  if(!res) return
  if(res.length === 0) {
    // 重置所有时间段状态
    timeSlots.value.forEach(slot => {
      const hour = slot.hour
      // 如果是今天，且时间已过，则锁定
      if (isCurrentTimePassed(hour)) {
        slot.status = 'locked'
      } else if (hour === 21) { // 21:00-22:00保持锁定
        slot.status = 'locked'
      } else {
        slot.status = 'available'
      }
    })
    return
  }
  
  const startHour = res[0].startHour
  const endHour = res[0].endHour
  const status = res[0].status
  
  // 添加空值检查
  if (!startHour || !endHour) {
    timeSlots.value.forEach(slot => {
      const hour = slot.hour
      // 如果是今天，且时间已过，则锁定
      if (isCurrentTimePassed(hour)) {
        slot.status = 'locked'
      } else if (hour === 21) { // 21:00-22:00保持锁定
        slot.status = 'locked'
      } else {
        slot.status = 'available'
      }
    })
    return
  }
  
  const start = parseInt(startHour.split(':')[0])
  const end = parseInt(endHour.split(':')[0])
  
  timeSlots.value.forEach(slot => {
    const hour = slot.hour
    // 如果是今天，且时间已过，则锁定
    if (isCurrentTimePassed(hour)) {
      slot.status = 'locked'
    } else if (hour === 21) { // 21:00-22:00保持锁定
      slot.status = 'locked'
    } else {
      // 根据预约状态更新
      slot.status = hour >= start && hour < end ? status : 'available'
    }
  })
}

// 提交预约表单
const toggleTimeSlot = (slot, index) => {
  if (slot.status !== 'available') return
  
  // 获取当前选中的时间段数量
  const selectedCount = timeSlots.value.filter(s => s.selected).length
  
  // 如果已经选择了两个时间段，清空所有选择
  if (selectedCount >= 2) {
    timeSlots.value.forEach(s => s.selected = false)
    form.value.startHour = ''
    form.value.endHour = ''
    // 设置新的开始时间
    slot.selected = true
    form.value.startHour = `${slot.hour.toString().padStart(2, '0')}:00:00`
    form.value.endHour = `${(slot.hour + 1).toString().padStart(2, '0')}:00:00`
    return
  }
  
  // 如果是第一次选择
  if (selectedCount === 0) {
    slot.selected = true
    form.value.startHour = `${slot.hour.toString().padStart(2, '0')}:00:00`
    form.value.endHour = `${(slot.hour + 1).toString().padStart(2, '0')}:00:00`
    return
  }
  
  // 如果是第二次选择
  const startSlot = timeSlots.value.find(s => s.selected)
  const startHour = startSlot.hour
  const endHour = slot.hour
  
  // 确保开始时间小于结束时间
  const minHour = Math.min(startHour, endHour)
  const maxHour = Math.max(startHour, endHour)
  
  // 检查中间是否有不可用的时间段
  let hasUnavailableSlot = false
  for (let i = minHour; i <= maxHour; i++) {
    if (timeSlots.value[i - 8].status !== 'available') {
      hasUnavailableSlot = true
      break
    }
  }
  
  // 如果中间有不可用的时间段，只选择当前点击的时间段
  if (hasUnavailableSlot) {
    timeSlots.value.forEach(s => s.selected = false)
    slot.selected = true
    form.value.startHour = `${slot.hour.toString().padStart(2, '0')}:00:00`
    form.value.endHour = `${(slot.hour + 1).toString().padStart(2, '0')}:00:00`
    return
  }
  
  // 如果中间都是可用的时间段，选择整个范围
  timeSlots.value.forEach(s => s.selected = false)
  for (let i = minHour; i <= maxHour; i++) {
    timeSlots.value[i - 8].selected = true
  }
  form.value.startHour = `${minHour.toString().padStart(2, '0')}:00:00`
  form.value.endHour = `${(maxHour + 1).toString().padStart(2, '0')}:00:00`
}

const submitForm = async () => {
  try {
    const reservationData = {
      userId: userStore.userId,
      roomId: props.roomId,
      ...form.value,
      startHour: form.value.startHour,
      endHour: form.value.endHour
    }
    await orderStore.createOrder(reservationData)
  } finally {
    emit('close')
  }
}

</script>

<style scoped>
.reservation-container {
  padding: 24px;
  background: white;
  border-radius: 16px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.card-header {
  margin-bottom: 24px;
  position: relative;
}

.card-header h2 {
  font-size: 24px;
  color: #1a237e;
  margin: 0;
  font-weight: 600;
  background: linear-gradient(90deg, #1a237e 0%, #3949ab 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-decoration {
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #3949ab 0%, #5c6bc0 100%);
  border-radius: 2px;
}

.reservation-form {
  width: 100%;
  margin: 0 auto;
  max-width: 900px;
}

.form-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.date-picker-item {
  margin-bottom: 0;
}

.number-input-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.custom-date-picker {
  width: 200px;
}

.custom-number-input {
  width: 120px;
}

.time-slots-container {
  margin: 20px auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  width: 95%;
  max-width: 900px;
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 16px;
  margin-top: 16px;
  width: 100%;
}

.time-slot-card {
  background: white;
  border-radius: 12px;
  padding: 16px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
  aspect-ratio: 1.2;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.time-slot-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.time-slot-card.selected {
  background: linear-gradient(135deg, #e8eaf6 0%, #c5cae9 100%);
  border-color: #3949ab;
}

.time-slot-card.locked {
  background: #fff5f5;
  border-color: #f56c6c;
}

.time-slot-card.booked {
  background: #fdf6ec;
  border-color: #e6a23c;
}

.time-slot-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 0 4px;
}

.time-label {
  font-size: 14px;
  font-weight: 500;
  color: #1a237e;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  text-align: center;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  width: 100%;
  justify-content: center;
  white-space: nowrap;
}

.status-indicator.available {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-indicator.booked {
  background: #fff3e0;
  color: #e65100;
}

.status-indicator.locked {
  background: #ffebee;
  color: #c62828;
}

.submit-button {
  background: linear-gradient(90deg, #3949ab 0%, #5c6bc0 100%);
  border: none;
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.submit-button:disabled {
  background: #e0e0e0;
  cursor: not-allowed;
  opacity: 0.7;
}

.cancel-button {
  background: #f5f5f5;
  border: none;
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

@media (max-width: 1200px) {
  .reservation-container {
    padding: 20px;
  }
  
  .time-slots-container {
    padding: 16px;
    width: 98%;
  }
  
  .time-slots-grid {
    grid-template-columns: repeat(5, 1fr);
  }
}

@media (max-width: 768px) {
  .reservation-container {
    padding: 16px;
  }

  .time-slots-container {
    padding: 12px;
    margin: 16px auto;
    width: 100%;
  }

  .time-slots-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
  }

  .time-slot-card {
    padding: 8px 4px;
  }

  .time-label {
    font-size: 12px;
  }

  .status-indicator {
    font-size: 10px;
    padding: 3px 4px;
  }

  .form-header {
    gap: 12px;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .number-input-item {
    margin-right: 0;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .submit-button,
  .cancel-button {
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .time-slots-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }
}
</style>